package com.coolingme.controller.test;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.coolingme.util.ResponseUtil;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;

/**
 * POI接口
 *
 * @author wangyue
 * @date 2020-08-09 18:01
 */
@Api(tags = "POI接口")
@ApiSupport(author = "wangyue", order = 998)
@ApiResponses({@ApiResponse(code = 200, message = "success"),
        @ApiResponse(code = 401, message = "Authentication Failure"),
        @ApiResponse(code = 402, message = "Login Information Invalid"),
        @ApiResponse(code = 403, message = "No Permission"), @ApiResponse(code = 420, message = "Data Error"),
        @ApiResponse(code = 421, message = "Cache Error"), @ApiResponse(code = 500, message = "Request fail")})
@RestController
@RequestMapping("/poi")
public class PoiController {

    @ApiOperation(value = "导出xlsx格式的Excel")
    @ApiOperationSupport(order = 1)
    @GetMapping("/writeXLSX/{error}")
    public void writeXLSX(HttpServletResponse response, @PathVariable("error") String error) {
        // 构造一些数据
        ArrayList<ArrayList<String>> rows = getListData();

        /*
        ExcelUtil.getWriter()默认创建xls格式的Excel，因此写出到客户端也需要自定义文件名为XXX.xls，否则会出现文件损坏的提示。
        若想生成xlsx格式，请使用ExcelUtil.getWriter(true)创建。
         */
//        ExcelWriter writer = ExcelUtil.getWriter(true);
        ExcelWriter writer = ExcelUtil.getBigWriter();

        // 默认设置标题样式
        writer.merge(rows.get(0).size() - 1, "HuTool导出Excel.xlsx");
        writer.write(rows, true);

        //out为OutputStream，需要写出到的目标流
        ServletOutputStream out = null;
        // excel名称
        String fileName = "test哈哈哈_" + System.currentTimeMillis() + ".xlsx";
        try {
            //response为HttpServletResponse对象
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
            // 设置文件名的编码方式，使得文件的名字能够正常安全的显示。
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            out = response.getOutputStream();
            if ("error".equals(error)) {
                System.out.println(1 / 0);
            }
            writer.flush(out, true);
        } catch (Exception e) {
            response.reset();
            response.setHeader("Content-type", "application/json;charset=utf-8");
            try {
                String result = ResponseUtil.error("导出失败：" + e.getMessage());
                response.getWriter().write(result);
                response.getWriter().flush();
            } catch (Exception ee) {
                ee.printStackTrace();
            }
        } finally {
            // 关闭writer和流
            writer.close();
            IoUtil.close(out);
        }
    }

    @ApiOperation(value = "导出xls格式的Excel")
    @ApiOperationSupport(order = 2)
    @GetMapping("/writeXLS")
    public void writeXLS(HttpServletResponse response) {
        // 构造一些数据
        ArrayList<ArrayList<String>> rows = getListData();

        // 通过工具类创建writer，默认创建xls格式
        ExcelWriter writer = ExcelUtil.getWriter();

        // 默认设置标题样式
        writer.merge(rows.get(0).size() - 1, "HuTool导出Excel.xls");
        writer.write(rows, true);

        //out为OutputStream，需要写出到的目标流
        ServletOutputStream out = null;
        // excel名称
        String fileName = "test_" + System.currentTimeMillis() + ".xls";
        try {
            //response为HttpServletResponse对象
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
            //test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            out = response.getOutputStream();
            writer.flush(out, true);
        } catch (IOException e) {
            e.printStackTrace();
            response.setHeader("Content-type", "application/json;charset=utf-8");
            try {
                response.getWriter().write(ResponseUtil.success("DownLoad Fail"));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        } finally {
            // 关闭writer和流
            writer.close();
            IoUtil.close(out);
        }
    }


    /**
     * 构造list数据
     */
    private ArrayList<ArrayList<String>> getListData() {
        ArrayList<String> head = CollUtil.newArrayList("姓名", "性别", "出生年月");
        ArrayList<String> row1 = CollUtil.newArrayList("zhangsan1", "男", "199701");
        ArrayList<String> row2 = CollUtil.newArrayList("zhangsan2", "男", "199702");
        ArrayList<String> row3 = CollUtil.newArrayList("zhangsan3", "男", "199703");
        ArrayList<String> row4 = CollUtil.newArrayList("zhangsan4", "男", "199704");
        ArrayList<ArrayList<String>> rows = CollUtil.newArrayList(head, row1, row2, row3, row4);
        return rows;
    }

}
